<?php
/**
 * Cost Model
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package models
 */
class Cost extends AppModel 
{
	/**
    * @var string Model name (faster in PHP 4)
    */
	var $name = 'Cost';
	
	/**
    * @var string displays field in select box
    */
	var $displayField = 'id';
		
	/**
    * @var array belongsTo relations
    */		
	var $belongsTo = array(
        'Country' => array(
            'className' => 'Country'
        ),
		'Usagetype' => array(
            'className' => 'Usagetype'
        ),
	);
	
	/**
	 * Function update
	 * 
	 * Updating costs
	 * @param integer $usagetype usagetype_id
	 * @param integer $country country_id
	 * @param integer $cost 
	 * @param integer $emmision
	 */
	function update($usagetype, $country, $cost, $emission) {
		$costData = $this->find('first', array(
			'conditions' => array(
				'Cost.country_id' => $country,
				'Cost.usagetype_id' => $usagetype,
			)
		));
		if(empty($costData)) {
			$this->create();
			$data = array('Cost' => array(
				'country_id' => $country,
				'usagetype_id' => $usagetype,
				'cost' => $cost,
				'emission' => $emission,
			));
			return $this->save($data);
		} else {
			$this->read(null, $costData['Cost']['id']);
			$this->set(array(
				'cost' => $cost, 
				'emission' => $emission
			));
			$this->save();
		}
	}
	
	/**
	 * Function findAllByCountryId
	 * 
	 * Find costs by country_id
	 * @param integer $id country_id
	 * @return array
	 */
	function findAllByCountryId($country) {
		$costs = parent::findAllByCountryId($country);
		$data = array();
		
		if(!empty($costs) && is_array($costs)) {
			foreach($costs AS $cost) {
				$data['Cost'][$cost['Usagetype']['id']] = array('cost' => $cost['Cost']['cost'], 'emission' => $cost['Cost']['emission']);
			}
		}
		return $data;
	}
}
